package user

import (
	"context"
	"time"

	"mall/common/resultx"
	"mall/service/backend/common/utils/jwt"
	"mall/service/backend/common/utils/pointy"
	"mall/service/user/api/internal/svc"
	"mall/service/user/api/internal/types"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	res, err := l.svcCtx.UserRpc.Login(l.ctx, &userclient.LoginReq{
		AuthType: req.AuthType,
		AuthKey:  req.AuthKey,
		Password: req.Password,
	})
	if err != nil {
		return nil, err
	}

	now := time.Now().Unix()
	accessExpire := l.svcCtx.Config.Auth.AccessExpire
	token, err := jwt.NewJwtToken(
		l.svcCtx.Config.Auth.AccessSecret,
		now,
		accessExpire,
		jwt.WithOption("userId", res.Id),
	)
	if err != nil {
		logx.Errorw("Login NewJwtToken err", logx.Field("detail", err.Error()))
		return nil, resultx.NewErrCode(resultx.USER_LOGIN_FAILED)
	}

	return &types.LoginResp{
		AccessToken:  pointy.GetPointer(token),
		AccessExpire: pointy.GetPointer(now + accessExpire),
		RefreshAfter: pointy.GetPointer(now + accessExpire / 2),
	}, nil
}
